package com.ruoyi.admin.service.app.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.admin.domain.LlmAppSettings;
import com.ruoyi.admin.domain.LlmDatasets;
import com.ruoyi.admin.mapper.LlmAppSettingsMapper;
import com.ruoyi.admin.service.app.LlmAppSettingsService;
import com.ruoyi.admin.service.faq.LlmFaqCategoryService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.MenuDO;
import com.ruoyi.common.core.domain.entity.RoleDO;
import com.ruoyi.common.core.domain.entity.RoleMenuDO;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StpSystemUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.common.utils.min_io.MinIOUtil;
import com.ruoyi.newSystem.mapper.MenuMapper;
import com.ruoyi.newSystem.mapper.RoleMapper;
import com.ruoyi.newSystem.mapper.RoleMenuMapper;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 应用设置服务实现类
 * </p>
 *
 * @author author
 * @since 2025-08-12
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class LlmAppSettingsServiceImpl extends ServiceImpl<LlmAppSettingsMapper, LlmAppSettings> implements LlmAppSettingsService {

    private final LlmAppSettingsMapper llmAppSettingsMapper;

    private final MenuMapper menuMapper;

    private final RoleMenuMapper roleMenuMapper;

//    private LlmMilvusService llmMilvusService;

    private final RoleMapper roleMapper;

    private final LlmFaqCategoryService llmFaqCategoryService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addAppSetting(LlmAppSettings llmAppSettings) {

//        try {
//            // 设置创建时间
//            llmAppSettings.setCreateTime(DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));
//            llmAppSettings.setUpdateTime(DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));
//
//            // 校验必填字段
//            if (StringUtils.isEmpty(llmAppSettings.getName())) {
//                return AjaxResult.error("应用名称不能为空");
//            }
//
//            // 检查名称是否已存在
//            LlmAppSettings existingApp = getAppSettingsByName(llmAppSettings.getName());
//            if (existingApp != null) {
//                return AjaxResult.error("应用名称已存在");
//            }
//
//            int result = llmAppSettingsMapper.insert(llmAppSettings);
//
//
//            //获取选择的智能应用和所有的菜单
//            String type = llmAppSettings.getType();
//            List<MenuDO> menuDOS = menuMapper.selectListByCategoryId(type);
//            //所有从菜单id
//            List<Long> menuIds = menuDOS.stream().map(MenuDO::getId).collect(Collectors.toList());
//
//
//            List<MenuDO> collect = menuDOS.stream().filter(item -> item.getType() == 5).collect(Collectors.toList());
//            List<String> datasetIds = new ArrayList<>();
//            for (MenuDO menuDO : collect) {
//                if ("cjzlgl".equals(menuDO.getPermission())) {
//                    IPage<LlmDatasets> datasets = llmMilvusService.getDatasets(1, 1000, null, null);
//                    List<LlmDatasets> records = datasets.getRecords();
//                    records.forEach(item -> {
//                        datasetIds.add(item.getId());
//                    });
//
//                } else {
//                    List<FaqCategory> faqCategoryVos = llmFaqCategoryService.queryRootFaqCategory("");
//                    faqCategoryVos.forEach(item -> {
//                        datasetIds.add(item.getId());
//                    });
//                }
//            }
//
//            //获取选择的角色
//            String character = llmAppSettings.getCharacter();
//            List<Long> strings = JSONArray.parseArray(character, Long.class);
//            //迭代角色
//            for (Long roleId : strings) {
//
//                //查询角色的知识库权限
//                RoleDO id = roleMapper.selectOne("id", roleId);
//                String dataScopeDatasetIds = id.getDataScopeDatasetIds();
//                Set<String> datasetIdsOld = new HashSet<>(datasetIds);
//                RoleDO roleDO = new RoleDO();
//                if (StringUtils.isNotBlank(dataScopeDatasetIds)) {
//                    JSONObject parse = JSONObject.parse(dataScopeDatasetIds);
//                    JSONArray knowledge = parse.getJSONArray("knowledge");
//                    List<String> list = knowledge.toList(String.class);
//                    datasetIdsOld.addAll(list);
//                }
//                //重新创建json 防止原数据没有json
//                JSONObject newScopeDataset = new JSONObject();
//                newScopeDataset.put("knowledge", datasetIdsOld);
//                roleDO.setDataScopeDatasetIds(JSONObject.toJSONString(newScopeDataset));
//                roleDO.setId(roleId);
//                //修改角色知识库权限
//                roleMapper.updateById(roleDO);
//
//                Set<Long> dbMenuIds = convertSet(roleMenuMapper.selectListByRoleId(roleId), RoleMenuDO::getMenuId);
//                // 将智能应用菜单与角色现在用的菜单合并然后入库
//                dbMenuIds.addAll(menuIds);
//
//                //删除这个角色所有菜单
//                roleMenuMapper.deleteListByRoleId(roleId);
//                //给这个角色添加合并后的菜单
//                roleMenuMapper.insertBatch(CollectionUtils.convertList(dbMenuIds, menuId -> {
//                    RoleMenuDO entity = new RoleMenuDO();
//                    entity.setRoleId(roleId);
//                    entity.setMenuId(menuId);
//                    entity.setCreateTime(LocalDateTime.now());
//                    entity.setModifyTime(LocalDateTime.now());
//                    return entity;
//                }));
//            }
//            return result > 0 ? AjaxResult.success("添加成功") : AjaxResult.error("添加失败");
//        } catch (Exception e) {
//            log.error("添加应用设置失败", e);
//            return AjaxResult.error("添加失败：" + e.getMessage());
//        }
        return AjaxResult.error("添加失败：");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateAppSetting(LlmAppSettings llmAppSettings) {

//        try {
//            if (llmAppSettings.getId() == null) {
//                return AjaxResult.error("应用设置ID不能为空");
//            }
//
//            // 设置更新时间
//            llmAppSettings.setUpdateTime(DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));
//
//            // 如果名称有变化，检查新名称是否已存在
//            if (StringUtils.isNotEmpty(llmAppSettings.getName())) {
//                LlmAppSettings existingApp = getAppSettingsByName(llmAppSettings.getName());
//                if (existingApp != null && !existingApp.getId().equals(llmAppSettings.getId())) {
//                    return AjaxResult.error("应用名称已存在");
//                }
//            }
//
//            int result = llmAppSettingsMapper.updateById(llmAppSettings);
//            //获取选择的智能应用和所有的菜单
//            String type = llmAppSettings.getType();
//
//            List<MenuDO> menuDOS = menuMapper.selectListByCategoryId(type);
//            //所有从菜单id
//            List<Long> menuIds = menuDOS.stream().map(MenuDO::getId).collect(Collectors.toList());
//            List<MenuDO> collect = menuDOS.stream().filter(item -> item.getType() == 5).collect(Collectors.toList());
//            List<String> datasetIds = new ArrayList<>();
//            for (MenuDO menuDO : collect) {
//                if ("知识库管理".equals(menuDO.getName())) {
//                    IPage<LlmDatasetsVo> datasets = llmMilvusService.getDatasets(1, 1000, null, null);
//                    List<LlmDatasetsVo> records = datasets.getRecords();
//                    records.forEach(item -> {
//                        datasetIds.add(item.getId());
//                    });
//
//                } else {
//                    List<FaqCategoryVo> faqCategoryVos = llmFaqCategoryService.queryRootFaqCategory("");
//                    faqCategoryVos.forEach(item -> {
//                        datasetIds.add(item.getId());
//                    });
//                }
//            }
//
//            //获取选择的角色
//            String character = llmAppSettings.getCharacter();
//            List<Long> strings = JSONArray.parseArray(character, Long.class);
//            //迭代角色
//            for (Long roleId : strings) {
//                //查询角色的知识库权限
//                RoleDO id = roleMapper.selectOne("id", roleId);
//                String dataScopeDatasetIds = id.getDataScopeDatasetIds();
//                Set<String> datasetIdsOld = new HashSet<>(datasetIds);
//                RoleDO roleDO = new RoleDO();
//                if (StringUtils.isNotBlank(dataScopeDatasetIds)) {
//                    JSONObject parse = JSONObject.parse(dataScopeDatasetIds);
//                    JSONArray knowledge = parse.getJSONArray("knowledge");
//                    List<String> list = knowledge.toList(String.class);
//                    datasetIdsOld.addAll(list);
//
//                }
//                //重新创建json 防止原数据没有json
//                JSONObject newScopeDataset = new JSONObject();
//                newScopeDataset.put("knowledge", datasetIdsOld);
//                roleDO.setDataScopeDatasetIds(JSONObject.toJSONString(newScopeDataset));
//                roleDO.setId(roleId);
//                //修改角色知识库权限
//                roleMapper.updateById(roleDO);
//
//                Set<Long> dbMenuIds = convertSet(roleMenuMapper.selectListByRoleId(roleId), RoleMenuDO::getMenuId);
//                // 将智能应用菜单与角色现在用的菜单合并然后入库
//                dbMenuIds.addAll(menuIds);
//
//                //删除这个角色所有菜单
//                roleMenuMapper.deleteListByRoleId(roleId);
//                //给这个角色添加合并后的菜单
//                roleMenuMapper.insertBatch(CollectionUtils.convertList(dbMenuIds, menuId -> {
//                    RoleMenuDO entity = new RoleMenuDO();
//                    entity.setRoleId(roleId);
//                    entity.setMenuId(menuId);
//                    entity.setCreateTime(LocalDateTime.now());
//                    entity.setModifyTime(LocalDateTime.now());
//                    return entity;
//                }));
//            }
//            return result > 0 ? AjaxResult.success("更新成功") : AjaxResult.error("更新失败");
//        } catch (Exception e) {
//            log.error("更新应用设置失败", e);
//            return AjaxResult.error("更新失败：" + e.getMessage());
//        }
        return AjaxResult.error("更新失败：");
    }

    @Override
    public LlmAppSettings getAppSettingsByName(String name) {
        return llmAppSettingsMapper.getAppSettingsByName(name);
    }

    @Override
    public IPage<LlmAppSettings> getByPage(Integer page, Integer size, LlmAppSettings llmAppSettings) {
        Page<LlmAppSettings> pageInfo = new Page<>(page, size);
        QueryWrapper<LlmAppSettings> queryWrapper = new QueryWrapper<>();

        // 构建查询条件
        if (llmAppSettings != null) {
            if (StringUtils.isNotEmpty(llmAppSettings.getName())) {
                queryWrapper.like("name", llmAppSettings.getName());
            }
            if (StringUtils.isNotEmpty(llmAppSettings.getType())) {
                queryWrapper.eq("type", llmAppSettings.getType());
            }
            if (StringUtils.isNotEmpty(llmAppSettings.getEnable())) {
                queryWrapper.eq("enable", llmAppSettings.getEnable());
            }
            if (StringUtils.isNotEmpty(llmAppSettings.getModel())) {
                queryWrapper.eq("model", llmAppSettings.getModel());
            }
            if (llmAppSettings.getRelease() != null) {
                queryWrapper.eq("release", llmAppSettings.getRelease());
            }
        }

        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");

        return this.page(pageInfo, queryWrapper);
    }

    @Override
    public List<LlmAppSettings> getAppSettingsByType(String type) {
        return llmAppSettingsMapper.getAppSettingsByType(type);
    }

    @Override
    public List<LlmAppSettings> getAppSettingsByEnable(String enable) {
        return llmAppSettingsMapper.getAppSettingsByEnable(enable);
    }

    @Override
    @Transactional
    public boolean publishApp(Integer id) {
        if (id == null) {
            return false;
        }

        UpdateWrapper<LlmAppSettings> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id)
                .set("release", true)
                .set("update_time", DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));

        return this.update(updateWrapper);
    }

    @Override
    @Transactional
    public boolean unpublishApp(Integer id) {
        if (id == null) {
            return false;
        }

        UpdateWrapper<LlmAppSettings> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id)
                .set("release", false)
                .set("update_time", DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));

        return this.update(updateWrapper);
    }

    @Override
    @Transactional
    public boolean batchPublishApps(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }

        UpdateWrapper<LlmAppSettings> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", ids)
                .set("release", true)
                .set("update_time", DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));

        return this.update(updateWrapper);
    }

    @Override
    @Transactional
    public boolean batchUnpublishApps(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }

        UpdateWrapper<LlmAppSettings> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", ids)
                .set("release", false)
                .set("update_time", DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));

        return this.update(updateWrapper);
    }

    @Override
    public List<LlmAppSettings> getAppSettingsByRelease(Boolean release) {
        return llmAppSettingsMapper.getAppSettingsByRelease(release);
    }

    @Override
    @Transactional
    public boolean toggleAppRelease(Integer id) {
        if (id == null) {
            return false;
        }

        // 先查询当前状态
        LlmAppSettings currentApp = this.getById(id);
        if (currentApp == null) {
            return false;
        }

        // 切换状态
        Boolean newReleaseStatus = currentApp.getRelease() == null ? true : !currentApp.getRelease();

        UpdateWrapper<LlmAppSettings> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id)
                .set("release", newReleaseStatus)
                .set("update_time", DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));

        return this.update(updateWrapper);
    }


    @Override
    public String uploadAppIcon(MultipartFile file) {

        String iconUrl = "";

        try {
            Map<String, String> map = MinIOUtil.putObject(file, "app/image/");

            iconUrl = map.get("fileUrl");

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return iconUrl;
    }


    @Override
    public void removeAppIcon(String iconUrl) {
        MinIOUtil.removeFile(iconUrl);
    }

    @Override
    public AjaxResult getGatewayPermissions() {
        //获取该用户所有角色
        if (StpSystemUtil.isAdmin()) {
            QueryWrapper<LlmAppSettings> llmAppSettingsQueryWrapper = new QueryWrapper<>();
            llmAppSettingsQueryWrapper.eq("enable", "Y");
            List<LlmAppSettings> llmAppSettings = llmAppSettingsMapper.selectList(llmAppSettingsQueryWrapper);
            return AjaxResult.success(llmAppSettings);
        }
        List<String> roleList = StpSystemUtil.getRoleList();
        if (roleList.isEmpty()) {
            return AjaxResult.success(new ArrayList<>());
        }
        //查询所有角色
        QueryWrapper<RoleDO> roleDOQueryWrapper = new QueryWrapper<>();
        roleDOQueryWrapper.in("code", roleList);
        List<RoleDO> roleDOS = roleMapper.selectList(roleDOQueryWrapper);
        List<Long> collect = roleDOS.stream().map(RoleDO::getId).collect(Collectors.toList());
        //获取角色所有菜单
        List<MenuDO> menuDOS = roleMenuMapper.selectListByRoleIds(collect);
        List<Long> menuIds = menuDOS.stream().map(MenuDO::getId).collect(Collectors.toList());
        //获取发布的智能应用
        QueryWrapper<LlmAppSettings> llmAppSettingsQueryWrapper = new QueryWrapper<>();
        llmAppSettingsQueryWrapper.eq("enable", "Y");
        List<LlmAppSettings> llmAppSettings = llmAppSettingsMapper.selectList(llmAppSettingsQueryWrapper);

        List<String> collect2 = menuIds.stream().map(Objects::toString).collect(Collectors.toList());
        List<LlmAppSettings> strings = new ArrayList<>();
        //取智能应用和权限的交集
        llmAppSettings.forEach(item -> {
            if (collect2.contains(item.getType())) {
                strings.add(item);
            }
        });

        return AjaxResult.success(strings);
    }

}
